/*
 * Filename:    KpiDataItemServiceImpl.java
 * Copyright:   2014 中国平安保险（集团）股份有限公司 版权所有
 * Company:     平安科技养老险及健康险系统开发部
 * Create at:   2014年10月11日
 */
package com.paic.mhis.hcpms.quota.calculationreport.calculationjob.biz.service.impl;

import java.util.Date;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.paic.mhis.hcpms.quota.calculationreport.calculationdataItem.biz.service.CalculationDataItemService;
import com.paic.mhis.hcpms.quota.calculationreport.calculationdataItem.dto.CalculationResultDTO;
import com.paic.mhis.hcpms.quota.calculationreport.calculationjob.biz.service.IKpiDataItemService;
import com.paic.mhis.hcpms.quota.calculationreport.calculationjob.biz.service.KpiJobCtrlService;
import com.paic.mhis.hcpms.quota.calculationreport.calculationjob.constants.CalculationJobConstants;
import com.paic.mhis.hcpms.quota.calculationreport.calculationjob.dto.HcpmsKpiJobCtrlDTO;
import com.paic.mhis.hcpms.quota.calculationreport.calculationjob.dto.HcpmsKpiJobParamDTO;
import com.paic.mhis.hcpms.quota.calculationreport.calculationjob.dto.KpiBatchDTO;
import com.paic.mhis.hcpms.quota.calculationreport.calculationjob.dto.KpiBatchDetailDTO;
import com.paic.mhis.hcpms.quota.calculationreport.calculationjob.dto.KpiBatchJobLogDTO;
import com.paic.mhis.hcpms.quota.calculationreport.calculationjob.dto.KpiBatchParamterDTO;
import com.paic.mhis.hcpms.quota.calculationreport.calculationjob.intergration.dao.KpiBatchDao;
import com.pingan.um.client.util.UUID;

/**
 * 数据项计算service实现类
 * 
 * @author DUQIFANG262
 * 
 */
@Component("kpiDataItemServiceImpl")
public class KpiDataItemServiceImpl implements IKpiDataItemService {
	public static Log log = LogFactory.getLog(KpiDataItemServiceImpl.class);

	@Autowired
	private KpiBatchDao kpiBatchDao;
	@Autowired
	private DateIdFactory kpiBatchSequenceIdService;
	@Autowired
	private CalculationDataItemService calculationDataItemService; // 数据项计算业务服务类
	@Autowired
	private KpiJobCtrlService kpiJobCtrlService;

	/**
	 * 
	 * 数据项计算job方法
	 * 
	 */

	@Override
	public void processDataItemCalculation() {

		log.info("-----数据项job进入-----");
		HcpmsKpiJobCtrlDTO ctrlDto = new HcpmsKpiJobCtrlDTO();
		ctrlDto.setJobCode("J20141217001");
		ctrlDto.setJobName("数据项计算JOB");
		ctrlDto.setTmpId(UUID.getID());
		ctrlDto.setJobStatus(CalculationJobConstants.CTRL_JOB_STATUS_USE);
		ctrlDto = kpiJobCtrlService.getHcpmsJobCtrl(ctrlDto);
		// if (ctrlDto != null) {
		//
		// ctrlDto.setJobStatus(CalculationJobConstants.CTRL_JOB_STATUS_USE);
		// kpiJobCtrlService.updateHcpmsJobCtrl(ctrlDto);
		// }
		if (ctrlDto == null) {
			log.info("-----没有数据进行数据项计算或者JOB被占用-----");
			return;
		}
		// String uuid = UUID.getID();

		// /更新批次主表状态是待处理且临时主建是null的
		// this.kpiBatchDao.updateKpiBatchDtoInfoTempBatchId(uuid);

		// 根据当前的临时主建和状态是待处理的00 加载出来
		KpiBatchParamterDTO paramter = new KpiBatchParamterDTO();
		paramter.setStatus(CalculationJobConstants.KPI_BATCH_STATUS_00);
		// paramter.setTempBatch(uuid);
		List<KpiBatchDTO> list = this.kpiBatchDao.queryKpiBatchDTOByStatus(paramter);

		if (null != list && list.size() > 0) {

			for (KpiBatchDTO bean : list) {

				KpiBatchParamterDTO paramterBean = new KpiBatchParamterDTO();

				String kpiBatchId = bean.getIdKpiBatch();
				String regionCode = bean.getRegionCode();
				String batchNo = bean.getBatchNo();
				String month = bean.getMonth();

				// 将当前批次的状态改成计算中
				paramterBean.setStatus(CalculationJobConstants.KPI_BATCH_STATUS_01);
				paramterBean.setKpiId(kpiBatchId);
				this.kpiBatchDao.updateKpiBatchDtoInfo(paramterBean);

				// 开始处理数据项计算
				log.info("-------数据项计算开始------");
				KpiBatchJobLogDTO logDto = new KpiBatchJobLogDTO();
				logDto.setBatchNo(batchNo);
				logDto.setCreateBy(bean.getCreatedBy());
				logDto.setUpdateBy(bean.getUpdatedBy());
				logDto.setCreateDate(new Date());
				logDto.setJobName(ctrlDto.getJobName());
				logDto.setJobNameDesc(KpiDataItemServiceImpl.class.getName());
				HcpmsKpiJobParamDTO dto = new HcpmsKpiJobParamDTO();
				dto.setBatchNo(batchNo);
				dto.setPeriod(CalculationJobConstants.KPI_PERIOD_MONTH);
				dto.setRegionCode(regionCode);
				dto.setMonth(month);
				CalculationResultDTO visitDataResultBean = this.calculationDataItemService.calculationVisitData(dto); // 就诊信息数据项计算
				logDto.setUpdateDate(new Date());
				logDto.setOpertionTime(new Date());
				logDto.setSuccessMessage(visitDataResultBean.getMessage(), regionCode, month);
				if (CalculationJobConstants.status_N.equals(visitDataResultBean.getIsError())) {
					logDto.setStatus(CalculationJobConstants.status_01);
				} else {
					logDto.setStatus(CalculationJobConstants.status_02);
					return;
				}
				kpiJobCtrlService.insertKpiJobLog(logDto);
				logDto.setCreateDate(new Date());
				CalculationResultDTO sigleDataItemResultBean = this.calculationDataItemService.calculationItemData(dto); // 单据信息数据项计算
				logDto.setUpdateDate(new Date());
				logDto.setOpertionTime(new Date());
				logDto.setSuccessMessage(sigleDataItemResultBean.getMessage(), regionCode, month);
				if (CalculationJobConstants.status_N.equals(sigleDataItemResultBean.getIsError())) {
					logDto.setStatus(CalculationJobConstants.status_01);

				} else {
					logDto.setStatus(CalculationJobConstants.status_02);
				}
				kpiJobCtrlService.insertKpiJobLog(logDto);
				log.info("-------数据项计算结束------");

				String visitDataStatus = visitDataResultBean.getIsError();
				// // 就诊信息数据项计算
				// 状态
				String sigleDataItemStaus = sigleDataItemResultBean.getIsError();
				// // // 单据信息数据项计算
				// // 状态
				// // 当就诊信息数据项计算正常且单据信息数据项计算 也正常
				if (CalculationJobConstants.status_N.equals(visitDataStatus)
						&& CalculationJobConstants.status_N.equals(sigleDataItemStaus)) {

					// 在指标批次明细表中插入一条记录
					this.insertKpiBatchDetailBean(bean);

					// 将当前批次的状态改成计算完成
					paramterBean.setStatus(CalculationJobConstants.KPI_BATCH_STATUS_02);
					paramterBean.setKpiId(kpiBatchId);
					// paramterBean.setTempBatch(uuid);
					this.kpiBatchDao.updateKpiBatchDtoInfo(paramterBean);

					// // 记录日志
					// this.saveExceuteResult(visitDataResultBean,
					// sigleDataItemResultBean, batchNo);

				} else {
					// 将当前批次的状态改成计算失败
					paramterBean.setStatus(CalculationJobConstants.KPI_BATCH_STATUS_20);
					paramterBean.setKpiId(kpiBatchId);
					paramterBean.setTempBatch("");
					this.kpiBatchDao.updateKpiBatchDtoInfo(paramterBean);
					// // 保存日志记录
					// this.saveExceuteResult(visitDataResultBean,
					// sigleDataItemResultBean, batchNo);

				}

			}

		} else {
			log.info("-----没有数据进行数据项计算-----");
		}
		ctrlDto.setJobStatus(CalculationJobConstants.CTRL_JOB_STATUS_IDLE);
		ctrlDto.setTmpId(null);
		kpiJobCtrlService.updateHcpmsJobCtrl(ctrlDto);
	}

	/**
	 * 
	 * @param visitDataResultBean
	 *            //就诊信息数据项计算
	 * @param sigleDataItemResultBean
	 * @param batchNo
	 */

	public void saveExceuteResult(CalculationResultDTO visitDataResultBean,
			CalculationResultDTO sigleDataItemResultBean, String batchNo) {

		String visitDataStatus = visitDataResultBean.getIsError(); // 就诊信息数据项计算状态
		String sigleDataItemStaus = sigleDataItemResultBean.getIsError(); // 单据信息数据项计算状态

		if (CalculationJobConstants.status_N.equals(visitDataStatus)) { // 就诊 正常

			this.saveKpiBatchJobLogDTOMethod(CalculationJobConstants.status_01, "就诊信息数据项计算正常", batchNo);

		} else if (CalculationJobConstants.status_Y.equals(visitDataStatus)) {

			this.saveKpiBatchJobLogDTOMethod(CalculationJobConstants.status_02, "{就诊信息数据项计算失败}异常{"
					+ visitDataResultBean.getMessage() + "}", batchNo);

		}

		if (CalculationJobConstants.status_N.equals(sigleDataItemStaus)) {// 单据正常

			this.saveKpiBatchJobLogDTOMethod(CalculationJobConstants.status_01, "单据信息数据项计算正常", batchNo);

		} else if (CalculationJobConstants.status_Y.equals(sigleDataItemStaus)) {

			this.saveKpiBatchJobLogDTOMethod(CalculationJobConstants.status_02, "{单据信息数据项计算失败}异常{"
					+ sigleDataItemResultBean.getMessage() + "}", batchNo);

		}

	}

	private void saveKpiBatchJobLogDTOMethod(String status, String exceptionMessage, String batchNo) {
		KpiBatchJobLogDTO bean = new KpiBatchJobLogDTO();
		bean.setBatchNo(batchNo);
		bean.setCreateBy("ADMIN");
		bean.setUpdateBy("ADMIN");
		bean.setJobExceptionMessage(exceptionMessage);
		bean.setJobName(KpiDataItemServiceImpl.class.getName());
		bean.setJobNameDesc("数据项计算job");
		bean.setOpertionTime(new Date());
		bean.setStatus(status);
		this.kpiBatchDao.insertBacthJobLogDTO(bean);
	}

	/**
	 * 保存指标批次明细表信息
	 * 
	 * @param kpiBatchBean
	 */
	private void insertKpiBatchDetailBean(KpiBatchDTO kpiBatchBean) {
		String batchDetailNo = this.kpiBatchSequenceIdService.getId(); // 生成批次明细表的批次号
		KpiBatchDetailDTO bean = new KpiBatchDetailDTO();
		bean.setBatchNo(kpiBatchBean.getBatchNo());
		bean.setBatchDetail(batchDetailNo);
		bean.setCreatedBy(kpiBatchBean.getCreatedBy());
		bean.setIsValid(CalculationJobConstants.KPI_IS_VALID_0);
		bean.setMonth(kpiBatchBean.getMonth());
		bean.setRegionCode(kpiBatchBean.getRegionCode());
		bean.setStatus(CalculationJobConstants.KPI_BATCH_STATUS_00);
		bean.setTmpBatch("");
		this.kpiBatchDao.insertKpiBatchDetailDtoInfo(bean);

	}
}
